// src/context/UserContext.tsx
import React, { createContext, useEffect, useState } from 'react';
import { STORAGE_KEY } from "../config/Constant.tsx";
import { userService } from '../api/service/UserService';
import type { User } from '../api/service/UserService';

export interface UserInfo {
    id: string;
    username: string;
    nickname?: string;
    avatar_addr?: string;
    access_token?: string;
    status?: string;
    create_time?: string;
    update_time?: string;
}

interface UserContextType {
    userInfo: UserInfo | null;
    setUserInfo: (userInfo: UserInfo | null) => void;
    isAuthenticated: boolean;
    logout: () => void;
    loading: boolean; // 添加加载状态

    // 用户管理相关
    users: User[];
    loadingUsers: boolean;
    error: string | null; // 添加错误状态
    fetchUsers: () => Promise<void>;
    refreshUsers: () => Promise<void>;
    updateUserStatus: (userId: string, status: string) => Promise<boolean>; // 添加更新用户状态方法
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [userInfo, setUserInfoState] = useState<UserInfo | null>(null);
    const [loading, setLoading] = useState(true); // 添加加载状态
    const [users, setUsers] = useState<User[]>([]);
    const [loadingUsers, setLoadingUsers] = useState(false);
    const [error, setError] = useState<string | null>(null); // 错误状态

    // 更新包装后的setUserInfo方法，确保同时更新state和localStorage
    const setUserInfo = (userInfo: UserInfo | null) => {
        setUserInfoState(userInfo);
        if (userInfo) {
            localStorage.setItem(STORAGE_KEY.USER_INFO, JSON.stringify(userInfo));
        } else {
            localStorage.removeItem(STORAGE_KEY.USER_INFO);
        }
    };

    useEffect(() => {
        // 应用启动时尝试从 localStorage 获取 user_info
        const storedUserInfo = localStorage.getItem(STORAGE_KEY.USER_INFO);
        if (storedUserInfo) {
            try {
                const parsedUserInfo = JSON.parse(storedUserInfo);
                setUserInfoState(parsedUserInfo);
            } catch (error) {
                console.error('解析用户信息失败:', error);
                // 如果解析失败，清除无效数据
                localStorage.removeItem(STORAGE_KEY.USER_INFO);
            }
        }
        // 设置加载完成
        setLoading(false);
    }, []);

    const logout = () => {
        setUserInfoState(null);
        localStorage.removeItem(STORAGE_KEY.USER_INFO);
    };

    // 获取用户列表
    const fetchUsers = async () => {
        setLoadingUsers(true);
        setError(null); // 清除之前的错误
        try {
            const result = await userService.getUsers();
            setUsers(result);
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '获取用户列表失败';
            setError(errorMessage);
            console.error('获取用户列表失败:', err);
        } finally {
            setLoadingUsers(false);
        }
    };

    // 刷新用户列表
    const refreshUsers = async () => {
        await fetchUsers();
    };

    // 更新用户状态
    const updateUserStatus = async (userId: string, status: string): Promise<boolean> => {
        try {
            const result = await userService.updateUserStatus(userId, status);
            if ( result) {
                // 更新用户列表中的用户状态
                setUsers(prevUsers =>
                    prevUsers.map(user =>
                        user.id === userId ? { ...user, status } : user
                    )
                );

                // 如果更新的是当前登录用户，也需要更新 userInfo 状态
                if (userInfo && userInfo.id === userId) {
                    setUserInfoState(prevUserInfo =>
                        prevUserInfo ? { ...prevUserInfo, status } : null
                    );
                }
            }
            return result;
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '更新用户状态失败';
            setError(errorMessage);
            console.error('更新用户状态失败:', err);
            return false;
        }
    };

    const isAuthenticated = !!(userInfo && userInfo.id && userInfo.username && userInfo.access_token);

    return (
        <UserContext.Provider value={{
            userInfo,
            setUserInfo,
            isAuthenticated,
            logout,
            loading, // 提供加载状态
            // 用户管理相关
            users,
            loadingUsers,
            error, // 提供错误状态
            fetchUsers,
            refreshUsers,
            updateUserStatus // 提供更新用户状态方法
        }}>
            {children}
        </UserContext.Provider>
    );
};

export default UserContext;
